package com.hcryan.djm.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.hcryan.djm.exception.BaiduMapException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * @author ryanwdj
 * @since 2025/2/23
 */
@Configuration
public class BaiduMapFeignConfig{

    @Bean
    public Decoder baiduMapFeignDecoder() {
        ObjectFactory<HttpMessageConverters> messageConverters = () -> {
            // 创建支持 text/javascript 的 Jackson 转换器
            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
            converter.setSupportedMediaTypes(Arrays.asList(
                    MediaType.APPLICATION_JSON,
                    MediaType.valueOf("text/javascript;charset=utf-8")  // 添加对 text/javascript 的支持
            ));
            return new HttpMessageConverters(converter);
        };
        return new SpringDecoder(messageConverters);
    }

    @Bean
    public ErrorDecoder baiduMapErrorDecoder(){
        return new BaiduMapErrorDecoder();
    }

    public static class BaiduMapErrorDecoder implements ErrorDecoder{

        private final ErrorDecoder defaultDecoder = new Default();

        @Override
        public Exception decode(String s, Response response) {

            try {
                String body = Util.toString(response.body().asReader());
                // 解析百度 API 的错误结构（假设返回 JSON 格式）
                JSONObject errorJson = JSON.parseObject(body);
                int status = errorJson.getInteger("status");
                String message = errorJson.getString("detailMessage");
                // 抛出自定义异常（需定义 BaiduMapException）
                throw new BaiduMapException(status, message);
            }catch (IOException | JSONException e){
                return defaultDecoder.decode(s, response);
            }
        }
    }
}
